package thread;

public class Demo04 implements Runnable {
    /**
     * 票数
     */
    private Integer tickets = 10;

    private boolean flag = true;

    @Override
    public void run() {
    /*    while (true) {
            if (tickets <= 0) {
                break;
            }
            try {
                // 模拟延时
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName() + "拿到了第" + tickets-- + "张票");
        }*/

        while (flag){
            try{
                buy();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

    private synchronized void buy() throws InterruptedException {
        if (tickets <= 0){
            flag = false;
            return;
        }
        Thread.sleep(400);
        System.out.println(Thread.currentThread().getName()+"买了第"+ tickets-- + "张票");
    }

    public static void main(String[] args) {
        Demo04 demo04 = new Demo04();
        new Thread(demo04,"tony").start();
        new Thread(demo04,"lucy").start();
        new Thread(demo04,"黄牛党").start();

        // 多个线程竞争使用统一份资源是导致第线程安全问题
    }
}
